package com.huilai.platform.country_platform.repository;

import com.huilai.platform.country_platform.model.ChatList;
import com.huilai.platform.country_platform.model.ChatMessage;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;

/**
 * 作者：洪霓
 * 日期：2023/3/27
 * 注释：
 */
public interface ChatMessageReposity extends JpaRepository<ChatMessage, Integer>, JpaSpecificationExecutor<ChatMessage> {

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "insert into chat_message(link_id, from_id, to_id, content, is_lastest)" +
            "values(:#{#chatMessage.linkId},:#{#chatMessage.fromId}, :#{#chatMessage.toId},:#{#chatMessage.content},:#{#chatMessage.isLastest})", nativeQuery = true)
    Integer addChatMessage(ChatMessage chatMessage);

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "update chat_message cm set cm.is_lastest = 0 where cm.link_id = :linkId and cm.is_lastest = 1",nativeQuery = true)
    Integer updateIsLastest(Integer linkId);

    ChatMessage findChatMessageByLinkIdAndFromIdAndIsLastest(Integer linkid, Integer fromId, Integer isLastest);
}
